/*
 * module_main.cpp
 *
 *  Created on: Jan 11, 2014
 *      Author: bohni
 */



#ifndef F_CPU
#define F_CPU 8000000UL
#endif

#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/eeprom.h>


#include "c_g_module_config.h"
#include "i2c_slave.h"
#include "hmc5883l.h"


void check_rec_code();
void scheduler_start();


int main () {

// STATE FLAGS
//	|	7	|	6	|	5 	|	4	|	3	|	2	|	1	|	0	|
//	|NEW_MAG|		|		|		|		|		|		|		|

	uint8_t state_flags = 0;

	SIGNAL_PIN_DDR |= (1<<SIGNAL_PIN);

	i2c_slave_init();
	scheduler_start();
	hmc5883l_init();


	sei();

	while (1) {

		if ( state_flags & 0x80 ) {
			hmc5883l_read_values();

			state_flags &= ~(0x80);
			SIGNAL_PORT |= (1<<SIGNAL_PIN);
		}


		if (i2c_state == TW_SR_DATA_ACK) {
			check_rec_code();
			SIGNAL_PORT &= ~(1<<SIGNAL_PIN);
		}
	}
return 0;
}


void check_rec_code() {

	switch (i2c_buffer[0]) {
	case RESTART_MODULE:

		// Watchdog einschalten
		WDTCR = ( 1 << WDE );
		// Dauerschleife
		while (1);
		break;

	case GET_NORTH:
		i2c_buffer[0] = (compass >> 8);
		i2c_buffer[1] = (compass & 0x00FF);
		break;
	case GET_MAGNET_VALUES:

		i2c_buffer[0] = (magnet.out_x >> 8);
		i2c_buffer[1] = (magnet.out_x  & 0x00FF);
		i2c_buffer[2] = (magnet.out_y >> 8);
		i2c_buffer[3] = (magnet.out_y  & 0x00FF);
		i2c_buffer[4] = (magnet.out_z >> 8);
		i2c_buffer[5] = (magnet.out_z  & 0x00FF);
		break;

	case COMPASS_SELF_TEST:
		hmc5883l_self_test();
		break;

	case COMPASS_TEMP_COMP:
		hmc5883l_temp_compensation();
		break;

	case GET_COMPASS_IDENT:
		i2c_buffer[0] = hmc5883l_read_reg(IDENTIFICATION_A);
		i2c_buffer[0] = hmc5883l_read_reg(IDENTIFICATION_B);
		i2c_buffer[0] = hmc5883l_read_reg(IDENTIFICATION_C);
		break;

		case GET_LOCATION:

		//TODO get location
		break;

	case READ_EEPROM:

		i2c_buffer[0] = eeprom_read_byte( (uint8_t*)i2c_buffer[1]);
		break;

	case UPDATE_EEPROM:
		eeprom_update_byte( (uint8_t*)i2c_buffer[1], i2c_buffer[2]);
		break;

	default:
		i2c_buffer[0] = 0xFF;
	}

}

void scheduler_start() {

}
